package com.weiyi.weiman.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.weiyi.weiman.domain.Const.UserConst;
import com.weiyi.weiman.exception.APIException;
import com.weiyi.weiman.mapper.user.UserMapper;
import com.weiyi.weiman.service.user.UserBalanceService;
import com.weiyi.weiman.service.user.UserService;
import com.weiyi.weiman.utils.JWTUtils;
import com.weiyi.weiman.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import user.User;

import java.util.concurrent.TimeUnit;

/**
 * @Author zhang
 * @Date 2021/5/14 下午10:53
 * @Description
 * @Version 1.0
 **/
@Service
@Slf4j
public class UserBalanceServiceImpl implements UserBalanceService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisUtils redisUtils;

    @Value("${weiman.exchangeRate}")
    private Integer exchangeRate;

    @Override
    public Long topUp(long amount, String token) {
        if (JWTUtils.validateJWT(token)) {
            String userId = JWTUtils.parseJWT(token).getSubject();
            User user = userService.getUser(Long.parseLong(userId));
            String userKey = UserConst.USER_DETAIL + userId;
            if (amount <= 0)
                throw new APIException("充值金额有误");
            amount *= exchangeRate;
            long balance = user.getBalance() + amount;
            System.out.println(user.getBalance() + "   "+ amount+"   "+balance);
            user.setBalance(balance);
            userMapper.updateById(user);
            redisUtils.hPut(userKey, "balance", balance+"");
            return balance;
        }
        return null;
    }

    @Override
    public Long getBalance(String token) {
        if (JWTUtils.validateJWT(token)) {
            String userId = JWTUtils.parseJWT(token).getSubject();
            String userKey = UserConst.USER_DETAIL + userId;
            userService.getUser(Long.parseLong(userId));
            Long balance = Long.parseLong(redisUtils.hGet(userKey, "balance").toString());
            return balance;
        }
        return null;
    }
}
